package com.servlet.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.servlet.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Title: ResponseServlet03
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/22 9:31
 */
@WebServlet("/resp03")
public class ResponseServlet03 extends HttpServlet {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 响应对象
        List<User> list =   Arrays.asList(
                new User("小明","123456",new Date()),
                new User("小红","123456",new Date()),
                new User("寒梅","123456",new Date()),
                new User("吉姆","123456",new Date()));

        // 将集合转为json
       String json =  objectMapper.writeValueAsString(list);



        // 响应文本信息
        // 设置响应解析的编码方式
//        resp.setCharacterEncoding("utf-8");
//        resp.setContentType("application/json");
        // 设置响应的类型 text/plain 文本类型 text/html 超文本类型 application/json json类型
         resp.setHeader("Content-Type","application/json;charset=utf-8");
        resp.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
